package cn.wang.open.common.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

import redis.clients.jedis.JedisPoolConfig;

/**
 * 默认的RedisTemplate实现，子系统自己定义则spring不会加载此bean
 */
@Configuration
public class RedisConfig {

	@Bean
	@ConfigurationProperties(prefix = "spring.redis.pool")
	public JedisPoolConfig getRedisConfig() {
		JedisPoolConfig config = new JedisPoolConfig();
		return config;
	}

	@Bean
	@ConfigurationProperties(prefix = "spring.redis")
	public JedisConnectionFactory getConnectionFactory() {
		JedisConnectionFactory factory = new JedisConnectionFactory();
		factory.setUsePool(true);
		JedisPoolConfig config = getRedisConfig();
		factory.setPoolConfig(config);
		return factory;
	}

	@Bean
	@ConditionalOnMissingBean(value = RedisTemplate.class)
	public RedisTemplate<?, ?> getRedisTemplate() {
		RedisTemplate<?, ?> template = new RedisTemplate<>();
		JedisConnectionFactory factory = getConnectionFactory();
		template.setConnectionFactory(factory);
		template.afterPropertiesSet();
		return template;
	}

}
